package com.cskaoyan.mall.filter;

import com.cskaoyan.mall.utils.Result;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName: AdminFilter
 * @Description: TODO
 * @Auther 庄左
 * @Date 2022/6/28 19:55
 * @Version
 **/

@WebFilter("/api/admin/*")
public class AdminFilter implements Filter {
    public void init(FilterConfig filterConfig){

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // response.setHeader("Access-Control-Allow-Origin", "http://localhost:8085");
        response.setHeader("Access-Control-Allow-Origin", "http://192.168.3.19:8085");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        //取session
        //哪些是需要验证登录，哪些是不需要验证登录？
        String requestURI = request.getRequestURI();
        String url = requestURI.replace(request.getContextPath()+"/api/admin/admin/","");
        String method = request.getMethod();
        if(!"OPTIONS".equals(method)){
            if(!"login".equals(url)){
                //如果请求的地址不是/api/admin/admin/login那么表示的是需要验证登录状态
                HttpSession session = request.getSession();
                String username = (String) session.getAttribute("name");
                Result result = new Result();
                result.setMessage("当前页面登录才可以访问");
                if(username == null){

                    //需要登录后才可以访问，但是此时没有登录
                    // response.getWriter().println(new Gson().toJson(result));

                    response.setHeader("refresh","0.01;url=http://192.168.3.19:8085/admin.html");

                    return;
                }
            }
        }


        filterChain.doFilter(request, response);

    }


    public void destroy() {

    }
}
